# !/usr/bin/env python3
# coding=utf8
"""
'主连'合约, 每个日期的数据, 是具体哪个合约的数据, 脚本是用来计算它的,
"""
import datetime
import pandas
import pathlib
import os
import sys
from typing import Any, Dict, List, Set, Tuple, Type, Optional, Union, Callable
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import tdxdata_converter  # NOQA: E402


def get_symbol_list(vt_symbol: str) -> List[str]:
    """"""
    symbol, exchange_str = vt_symbol.split(".")
    l789: Dict[str, bool] = {_: True for _ in ("L7", "L8", "L9") if symbol.endswith(_)}  # 次连/主连/指数
    assert len(l789) == 1
    #
    filepath: Optional[str] = tdxdata_converter.guess_filename(
        exchange=tdxdata_converter.Exchange(exchange_str).value,
        symbol=symbol,
        interval=tdxdata_converter.Interval.DAILY.value,
        basepath=r"C:\new_tdx\vipdoc",
        output=print,
    )
    filepath: pathlib.Path = pathlib.Path(filepath)
    int_sharp_product: str = filepath.name.removesuffix(filepath.suffix).removesuffix(list(l789.keys())[0])
    pattern: str = f"{int_sharp_product}*{filepath.suffix}"
    paths: List[pathlib.Path] = [_ for _ in filepath.parent.glob(pattern=pattern)]
    path_: List[pathlib.Path] = []
    for path in paths:
        _ = [_ for _ in ("L7", "L8", "L9") if path.name.removesuffix(path.suffix).endswith(_)]
        if _:
            continue
        path_.append(path)
    paths: List[pathlib.Path] = sorted(path_)

    symbols: List[str] = []

    for path in paths:
        value: str = path.name.removesuffix(path.suffix)
        fields: List[str] = value.split(sep="#", maxsplit=1)
        symbols.append(fields[1])

    return symbols


def calculate(vt_symbol: str):
    """"""
    symbols: List[str] = get_symbol_list(vt_symbol=vt_symbol)
    symbol, exchange_str = vt_symbol.split(".")
    #
    df_BASE: pandas.DataFrame = tdxdata_converter.get_tdx_price(
        exchange=tdxdata_converter.Exchange(exchange_str).value,
        symbol=symbol,
        interval=tdxdata_converter.Interval.DAILY.value,
        start=datetime.datetime(year=1990, month=12, day=19),
        end=datetime.datetime(year=2099, month=12, day=31),
        start_business_day=None,
        end_business_day=None,
        basepath=r"C:\new_tdx\vipdoc",
        days=[],
        output=print,
    )
    #
    cache: Dict[str, pandas.DataFrame] = {}
    #
    for one_symbol in symbols:
        one_df: pandas.DataFrame = tdxdata_converter.get_tdx_price(
            exchange=tdxdata_converter.Exchange(exchange_str).value,
            symbol=one_symbol,
            interval=tdxdata_converter.Interval.DAILY.value,
            start=datetime.datetime(year=1990, month=12, day=19),
            end=datetime.datetime(year=2099, month=12, day=31),
            start_business_day=None,
            end_business_day=None,
            basepath=r"C:\new_tdx\vipdoc",
            days=[],
            output=print,
        )
        cache[one_symbol] = one_df
    #
    mapping: Dict[pandas.Timestamp, dict] = {}
    #
    for timestamp in df_BASE.index:
        assert isinstance(timestamp, pandas.Timestamp)
        df4base: pandas.DataFrame = df_BASE[timestamp:timestamp]
        for sym, df_curr in cache.items():
            df4curr = df_curr[timestamp:timestamp]
            assert max(len(df4base), len(df4curr)) <= 1
            if df4base.equals(df4curr):
                assert mapping.get(timestamp) is None
                mapping[timestamp] = {"dttm": timestamp, "symbol": sym}
        if mapping.get(timestamp) is None:
            mapping[timestamp] = {"dttm": timestamp, "symbol": None}
    #
    df_rslt = pandas.DataFrame(mapping.values())
    df_rslt.set_index(keys=["dttm"], drop=True, inplace=True)
    pandas.set_option('display.max_rows', None)  # 显示所有行
    #
    print(df_rslt)


if __name__ == "__main__":
    vt_symbol: str = sys.argv[1] if 2 <= len(sys.argv) else "MAL8.CZCE"
    calculate(vt_symbol=vt_symbol)
